package com.example.isoftservice.service.impl;

import com.example.isoftservice.mapper.NewsMapper;
import com.example.isoftservice.pojos.News;
import com.example.isoftservice.service.NewsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NewsServiceImpl implements NewsService {

    @Resource
    private NewsMapper newsMapper;

    @Override
    @Cacheable(cacheNames ="new",key="#pageNo+pageSize")
    public Map<String, Object> searchNewsList(Integer pageNum, Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        PageHelper.startPage(pageNum,pageSize);
        List<Map<String,Object>> resultList = newsMapper.selectNewsList();
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(resultList);
        map.put("total",pageInfo.getTotal());
        map.put("rows",pageInfo.getList());
        return map;
    }

    @Override
    @Cacheable(cacheNames ="new",key="#newsId")

    public News searchNewsById(Integer newsId) {
        return newsMapper.selectNewsById(newsId);
    }

    @Override
    @CacheEvict(cacheNames = "new" ,allEntries = true)
    public Boolean addNews(News news) {
        news.setCreateTime(new Date(System.currentTimeMillis()));
        int count = newsMapper.insertNews(news);
        return count==1 ? true : false;
    }

    @Override
    @CacheEvict(cacheNames = "new" ,allEntries = true)
    public Boolean removeNews(Integer[] ids) {
        return newsMapper.deleteByIds(ids) >= 1 ? true : false;
    }

    @Override
    @CacheEvict(cacheNames = "new" ,allEntries = true)
    public Boolean modifyNews(News news) {
        return newsMapper.updateNewsById(news) == 1 ? true : false;
    }
}
